package compress

import (
	"bytes"
	"io"
	"log"

	"github.com/klauspost/compress/zstd"
)

// compressZstd 压缩
func compressZstd(in io.Reader, out io.Writer) error {
	enc, _ := zstd.NewWriter(out)

	_, err := io.Copy(enc, in)
	if err != nil {
		enc.Close()
		return err
	}
	return enc.Close()
}

// DecompressZstd 解压
func decompressZstd(in io.Reader, out io.Writer) error {
	d, err := zstd.NewReader(in)
	if err != nil {
		return err
	}
	defer d.Close()

	_, err = io.Copy(out, d)
	return err
}

func DecompressData(data []byte) (retData []byte, err error) {
	var out = new(bytes.Buffer)
	err = decompressZstd(bytes.NewBuffer(data), out)
	if err != nil {
		// 解压失败，可能是文件保存错误
		log.Println("解压失败，", err)
		return
	}
	retData = out.Bytes()
	return
}

func CompressData(data []byte) (retData []byte, err error) {
	var out = new(bytes.Buffer)
	err = compressZstd(bytes.NewBuffer(data), out)
	if err != nil {
		log.Fatalln("压缩过程中，未测试过异常", err)
	}
	retData = out.Bytes()
	return
}
